import com.gzkit.crm.mcs.mapper.TimedTaskMapper;
import com.gzkit.crm.mcs.utils.CacheUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import pres.lnk.springframework.AbstractScheduler;

import java.util.concurrent.TimeUnit;

/**
 *
 * @Author lnk
 * @Date 2018/2/28
 */
public class MysqlSchedulerImpl extends AbstractScheduler {
    private static final String MAX_LEVEL = "maxLevel";

    @Autowired
    private TimedTaskMapper timedTaskMapper;

    @Override
    public boolean check(String id) {
        int count = timedTaskMapper.check(id);
        return count == 0;
    }

    @Override
    public boolean lock(String id, long timeoutMillis) {
        long timeout = timeoutMillis / 1000;
        int result = timedTaskMapper.hasId(id);
        if(result > 0){
            try {
                result = timedTaskMapper.lock(id, timeout);
            } finally { }
        }else{
            try {
                result = timedTaskMapper.insert(id, timeout, null);
            } finally { }
        }
        return result == 1;
    }

    @Override
    public void relock(String id, long timeoutMillis) {
        long timeout = timeoutMillis / 1000;
        timedTaskMapper.update(id, timeout, null);
    }

    @Override
    public long currentTimeMillis() {
        return timedTaskMapper.time();
    }

    @Override
    public void keepAlive() {
        int timeout = getHeartTime() + 5;

        //获取当前最高level
        String value = timedTaskMapper.getMaxLevel(MAX_LEVEL);
        Integer result = null;
        if(NumberUtils.isDigits(value)){
            result = Integer.parseInt(value);
        }

        if(result == null){
            //如果数据库没有保存level，则保存当前服务器的级别到数据库
            try {
                timedTaskMapper.insert(MAX_LEVEL, timeout, getLevel() + "");
            } catch (Exception e){
                timedTaskMapper.updateLevel(MAX_LEVEL, getLevel() + "", timeout);
            }
        }else{
            //数据库已有level
            if(result == getLevel()){
                //如果数据库level与当前服务器相同，则尝试刷新当前级别服务器的时间
                try {
                    timedTaskMapper.updateLevelTime(MAX_LEVEL, getLevel() + "", timeout);
                } finally { }
            }else if(result > getLevel()){
                //如果当前服务器级别比数据库的高，则刷新数据库级别
                try {
                    timedTaskMapper.updateLevel(MAX_LEVEL, getLevel() + "", timeout);
                } finally { }
            }

        }
    }

    @Override
    public int getMaxAliveLevel() {
        String value = timedTaskMapper.getMaxLevel(MAX_LEVEL);
        if(NumberUtils.isDigits(value)){
            return Integer.parseInt(value);
        }
        return getLevel();
    }
}